import React, { useEffect, useState } from 'react'
import { Button, Checkbox, Drawer, Input, InputNumber, message, Space, Table } from 'antd'
import PageContainer from '@/components/PageContainer'
import { ITableData, PurchaseOrderCommodityVO } from '../types'
import CustomTable from '@/components/CustomTable'
import './index.less'
import { useDetailedDetailedColumns } from '../columns'
import {
  getPurchaseCommodity,
  getPurchaseSummarize,
  updatePurchaseAppointmentFloatingLimit,
  updateTagPrice,
  updatePurchaseCommodity,
} from '@/api/purchase'
import * as mathjs from 'mathjs'
import { EditOutlined } from '@ant-design/icons'
import { useAppSelector } from '@/store/hooks'
import { applicationTypeEnum } from '@/constant'
import PermissionButton from '@/components/PermissionButton'
const Index = (props: { detailInfo: Record<string, any>; getDetail: () => void }) => {
  const [isEdit, setIsEdit] = useState(false)
  const [batchEdit, setbatchEdit] = useState(false)
  const [isCommonPrice, setisCommonPrice] = useState(true)
  const [tableData, settableData] = useState<PurchaseOrderCommodityVO[]>([])
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [PurchaseSummarize, setPurchaseSummarize] = useState<Record<string, any>>({})
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  useEffect(() => {
    getDetail()
    getPurchaseSummarizeData()
  }, [])
  const getDetail = async () => {
    const res = await getPurchaseCommodity<PurchaseOrderCommodityVO>({
      purchaseOrderCode: props.detailInfo.purchaseOrderCode,
    })
    if (res.code === 200) {
      settableData(res.data)
    }
  }
  const getPurchaseSummarizeData = async () => {
    const res = await getPurchaseSummarize({
      purchaseOrderCode: props.detailInfo.purchaseOrderCode,
    })
    if (res.code === 200) {
      setPurchaseSummarize(res.data)
    }
  }
  const handleLimit = () => {
    setIsEdit(true)
  }
  const onSave = async (tableData: PurchaseOrderCommodityVO[]) => {
    console.log(tableData, 'rr')
    const res = await updatePurchaseCommodity(tableData).finally(() => {
      getDetail()
      getPurchaseSummarizeData()
    })
    if (res.code === 200) {
      message.success('操作成功')
    }
  }
  return (
    <PageContainer className="detailed_page_wrap">
      <div className="dpw_top">
        <div className="dpwt_item">
          订单数量：<span>{PurchaseSummarize.totalQty || '-'}</span>
        </div>
        <div className="dpwt_item">
          订单金额：<span>{PurchaseSummarize.totalAmount || '-'}</span>
        </div>
        <div className="dpwt_item">
          总吊牌额：<span>{PurchaseSummarize.totalTagAmount || '-'}</span>
        </div>
        <div className="dpwt_item">
          已到货数量：<span>{PurchaseSummarize.deliveryQty || '-'}</span>
        </div>
        <div className="dpwt_item">
          已到货金额：<span>{PurchaseSummarize.deliveryAmount || '-'}</span>
        </div>
        <div className="dpwt_item">
          未到数量：<span>{PurchaseSummarize.notDeliveryQty || '-'}</span>
        </div>
      </div>
      <div className="dpw_actions">
        <div>预约数量浮动上限：</div>
        <div>
          {isEdit ? (
            <InputNumber
              defaultValue={props?.detailInfo?.appointmentFloatingLimit || ''}
              className="ckbox_input_style"
              precision={2}
              min={0}
              max={100}
              onBlur={async (event: any) => {
                const data = event.target.value < 0 ? 0 : event.target.value > 100 ? 100 : event.target.value
                const res = await updatePurchaseAppointmentFloatingLimit({
                  id: props.detailInfo.id,
                  purchaseOrderCode: props.detailInfo.purchaseOrderCode,
                  appointmentFloatingLimit: data,
                })
                if (res.code === 200) {
                  message.success('操作成功')
                  typeof props.getDetail === 'function' && props.getDetail()
                  setIsEdit(false)
                }
              }}
            ></InputNumber>
          ) : props?.detailInfo?.appointmentFloatingLimit ? (
            props?.detailInfo?.appointmentFloatingLimit + '%'
          ) : (
            '-'
          )}
        </div>
        {isRoot &&
        buttonCodeList.includes('editDeliverLimitByOrder') &&
        (props?.detailInfo?.status == 0 || props?.detailInfo?.status == 1 || props?.detailInfo?.status == 2) ? (
          <EditOutlined
            style={{ color: 'var(--primary-color)', cursor: 'pointer', marginLeft: 4 }}
            onClick={() => handleLimit()}
          />
        ) : null}
      </div>
      {props?.detailInfo.status == 0 ? (
        <div style={{ margin: '10px' }}>
          <PermissionButton
            permission="editPurchaseTagPrice"
            type="primary"
            onClick={async () => {
              const res = await updateTagPrice({ purchaseOrderCode: props.detailInfo.purchaseOrderCode })
              if (res.code === 200) {
                message.success('操作成功')
                getDetail()
                getPurchaseSummarizeData()
              }
            }}
          >
            更新吊牌价
          </PermissionButton>
        </div>
      ) : null}
      <div className="custom_table_style">
        {props?.detailInfo?.status == 0 && buttonCodeList?.includes('editPurchaseGoods') && (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', marginBottom: 6 }}>
            <Checkbox checked={isCommonPrice} onChange={(event) => setisCommonPrice(event.target.checked)}>
              采购价格按款式统一
            </Checkbox>
          </div>
        )}
        <Table
          pagination={false}
          bordered
          columns={useDetailedDetailedColumns({
            detailInfo: props.detailInfo,
            tableData,
            settableData,
            onSave,
            isRoot,
            canEdit: buttonCodeList.includes('editPurchaseGoods'),
            getDetail,
            batchEdit,
            setbatchEdit,
            isCommonPrice,
          })}
          dataSource={tableData}
          scroll={{
            x: 'max-content',
          }}
          rowKey={(rows) => rows.skuCode}
          summary={(tableData) => (
            <Table.Summary>
              <Table.Summary.Row>
                <Table.Summary.Cell index={0} align="center">
                  求和
                </Table.Summary.Cell>
                <Table.Summary.Cell
                  index={1}
                  colSpan={props.detailInfo?.status == 0 && buttonCodeList.includes('editPurchaseGoods') ? 8 : 7}
                ></Table.Summary.Cell>
                <Table.Summary.Cell index={2} align="center">
                  {/* 下单数量 */}
                  {tableData?.reduce(
                    (pre, item) => mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.orderQty || 0)).toString(),
                    0,
                  )}
                </Table.Summary.Cell>
                <Table.Summary.Cell index={3} colSpan={1}></Table.Summary.Cell>
                <Table.Summary.Cell index={4} align="center">
                  {/* 采购金额 */}
                  {tableData?.reduce(
                    (pre, item) =>
                      mathjs
                        .add(
                          mathjs.bignumber(pre),
                          mathjs.bignumber(
                            mathjs.multiply(
                              mathjs.bignumber(item?.orderQty || 0),
                              mathjs.bignumber(item?.purchasePrice || 0),
                            ) || 0,
                          ),
                        )
                        .toString(),
                    0,
                  )}
                </Table.Summary.Cell>
                <Table.Summary.Cell index={5}></Table.Summary.Cell>
                <Table.Summary.Cell index={6} align="center">
                  {/* 吊牌金额 */}
                  {tableData?.reduce(
                    (pre, item) =>
                      mathjs
                        .add(
                          mathjs.bignumber(pre),
                          mathjs.multiply(
                            mathjs.add(
                              mathjs.bignumber(item.directSaleQty || 0),
                              mathjs.bignumber(item.franchisingQty || 0),
                              mathjs.bignumber(item.onlineQty || 0),
                            ),
                            mathjs.bignumber(item?.tagPrice || 0),
                          ),
                        )
                        .toString(),
                    0,
                  )}
                </Table.Summary.Cell>
                <Table.Summary.Cell index={7} align="center">
                  {tableData?.reduce(
                    (pre, item) =>
                      mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.scheduledQty || 0)).toString(),
                    0,
                  )}
                </Table.Summary.Cell>
                <Table.Summary.Cell index={8} colSpan={1}></Table.Summary.Cell>
                <Table.Summary.Cell index={9} align="center">
                  {tableData?.reduce(
                    (pre, item) =>
                      mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.deliveryQty || 0)).toString(),
                    0,
                  )}
                </Table.Summary.Cell>
                <Table.Summary.Cell index={10} colSpan={1}></Table.Summary.Cell>
                {isRoot && (
                  <>
                    <Table.Summary.Cell index={11} align="center">
                      {tableData?.reduce(
                        (pre, item) =>
                          mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.directSaleQty || 0)).toString(),
                        0,
                      )}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={12} align="center">
                      {tableData?.reduce(
                        (pre, item) =>
                          mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.franchisingQty || 0)).toString(),
                        0,
                      )}
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={13} align="center">
                      {tableData?.reduce(
                        (pre, item) =>
                          mathjs.add(mathjs.bignumber(pre), mathjs.bignumber(item?.onlineQty || 0)).toString(),
                        0,
                      )}
                    </Table.Summary.Cell>
                  </>
                )}
              </Table.Summary.Row>
            </Table.Summary>
          )}
        />
      </div>
    </PageContainer>
  )
}

export default Index
